﻿using System.Linq;
using Microsoft.SharePoint;
using NUnit.Framework;
using SharePoint.Orm.TestHelpers;
using SPGeneratedWithFinders;
using SPGeneratedWithFinders.ContentTypes;
using SPGeneratedWithFinders.Lists;

namespace SharePoint.Orm {
	[TestFixture]
	public class SPFinderDataContextTest : TestBase {
		private int _item1Id;
		private int _item2Id;
		private MySPDataContext _ctx;

		[TestFixtureSetUp]
		public override void TestInitialize() {
			base.TestInitialize();
			SiteHelpers.EnsureSite();
			SiteHelpers.RemoveData();

			_ctx = MySPDataContextAccessor.Create(SiteHelpers.Url);

			SPList list = SiteHelpers.EnsureList1(_ctx.Site);

			SPListItem item1 = list.Items.Add();
			item1["Title"] = "Item1";
			item1[SiteHelpers.Field1Name] = "Item1";
			item1.Update();
			_item1Id = item1.ID;

			SPListItem item2 = list.Items.Add();
			item2["Title"] = "Item1";
			item2[SiteHelpers.Field1Name] = "Item2";
			item2.Update();
			_item2Id = item2.ID;
		}

		[TestFixtureTearDown]
		public override void TestCleanup() {
			base.TestCleanup();
			_ctx.Dispose();
		}

		[Test]
		public void TestContentTypeFindAll() {
			ContentType1[] all = ContentType1.Finder.FindAll<List1>().ToArray();
			Assert.AreEqual(2, all.Length);
			Assert.IsTrue(all.Any(i => i.Id == _item1Id));
			Assert.IsTrue(all.Any(i => i.Id == _item2Id));
		}

		[Test]
		public void TestContentTypeFindById() {
			ContentType1 item = ContentType1.Finder.FindById<List1>(_item1Id);
			Assert.AreEqual(_item1Id, item.Id);
		}

		[Test]
		public void TestListFindAll() {
			List1[] all = List1.Finder.FindAll().Cast<List1>().ToArray();
			Assert.AreEqual(2, all.Length);
			Assert.IsTrue(all.Any(i => i.Id == _item1Id));
			Assert.IsTrue(all.Any(i => i.Id == _item2Id));
		}

		[Test]
		public void TestListFindById() {
			List1 item = List1.Finder.FindById(_item1Id);
			Assert.AreEqual(_item1Id, item.Id);
		}
	}
}
